package com.kmproject.haifu.mvp.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.KeyboardUtils;
import com.blankj.utilcode.util.StringUtils;
import com.jess.arms.base.BaseActivity;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.jess.arms.widget.CustomPopupWindow;
import com.kmproject.haifu.R;
import com.kmproject.haifu.app.utils.ExtensionUtilKt;
import com.kmproject.haifu.di.component.DaggerConvenientPaymentComponent;
import com.kmproject.haifu.mvp.contract.ConvenientPaymentContract;
import com.kmproject.haifu.mvp.model.api.Api;
import com.kmproject.haifu.mvp.model.entity.beans.ExchangeRateBean;
import com.kmproject.haifu.mvp.model.entity.beans.HousePayWayBean;
import com.kmproject.haifu.mvp.model.entity.beans.MemberPayResultBean;
import com.kmproject.haifu.mvp.model.entity.resbean.ReqParamsRecharge;
import com.kmproject.haifu.mvp.presenter.ConvenientPaymentPresenter;
import com.kmproject.haifu.mvp.ui.widget.MonitorDrawableEventEditText;
import com.tencent.mm.sdk.modelbase.BaseResp;
import com.widget.picker.PickerDateUtil;
import com.widget.picker.bis.CustomDatePickerDialog;
import com.widget.picker.bis.DataPickerDialog;

import org.simple.eventbus.Subscriber;
import org.simple.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

import butterknife.BindView;
import butterknife.OnClick;

import static com.jess.arms.utils.Preconditions.checkNotNull;


/**
 * ================================================
 * Description：便民业务
 * <p>
 * Created by MVPArmsTemplate on 08/28/2019 15:44
 * <a href="mailto:jess.yan.effort@gmail.com">Contact me</a>
 * <a href="https://github.com/JessYanCoding">Follow me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms">Star me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms/wiki">See me</a>
 * <a href="https://github.com/JessYanCoding/MVPArmsTemplate">模版请保持更新</a>
 * ================================================
 */
public class ConvenientPaymentActivity extends BaseActivity<ConvenientPaymentPresenter> implements ConvenientPaymentContract.View {
    @BindView(R.id.ll_root_view)
    LinearLayout ll_root_view;
    @BindView(R.id.tv_convenient_payment_service_provider)
    TextView tv_convenient_payment_service_provider;

    @BindView(R.id.tv_convenient_payment_bill_no_l)
    TextView tv_convenient_payment_bill_no_l;
    @BindView(R.id.et_convenient_payment_bill_no)
    MonitorDrawableEventEditText et_convenient_payment_bill_no;

    @BindView(R.id.i_convenient_payment_mobile)
    View i_convenient_payment_mobile;
    @BindView(R.id.ll_convenient_payment_mobile)
    LinearLayout ll_convenient_payment_mobile;
    @BindView(R.id.et_convenient_payment_mobile)
    EditText et_convenient_payment_mobile;

    @BindView(R.id.i_convenient_payment_date)
    View i_convenient_payment_date;
    @BindView(R.id.ll_convenient_payment_date)
    LinearLayout ll_convenient_payment_date;
    @BindView(R.id.tv_convenient_payment_date_l)
    TextView tv_convenient_payment_date_l;
    @BindView(R.id.ll_convenient_payment_date_r)
    LinearLayout ll_convenient_payment_date_r;
    @BindView(R.id.tv_convenient_payment_date)
    TextView tv_convenient_payment_date;

    @BindView(R.id.et_convenient_payment_amount)
    EditText et_convenient_payment_amount;
    @BindView(R.id.tv_release_rent_seeking_bottom_operation)
    TextView tv_release_rent_seeking_bottom_operation;

    private String bisType = Api.ELECTRICITY_TYPE;

    private List<HousePayWayBean> mServiceProviderList;
    private ReqParamsRecharge reqParamsRecharge;

    @Override
    public void setupActivityComponent(@NonNull AppComponent appComponent) {
        DaggerConvenientPaymentComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .view(this)
                .build()
                .inject(this);
    }

    @Override
    public int initView(@Nullable Bundle savedInstanceState) {
        return R.layout.activity_convenient_payment; //如果你不需要框架帮你设置 setContentView(id) 需要自行设置,请返回 0
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        Intent intent = getIntent();
        reqParamsRecharge = new ReqParamsRecharge();
        bisType = intent.getStringExtra("BIS_TYPE");

        switch (bisType) {
            case Api.ELECTRICITY_TYPE:
                setTitle("缴纳电费");
                initElectricityView();

                reqParamsRecharge.setInvestType("electricity");//充值类型：mobile话费，electricity电费，water水费,network网费,必填
                break;
            case Api.WATER_TYPE:
                setTitle("缴纳水费");
                initWaterView();

                reqParamsRecharge.setInvestType("water");//充值类型：mobile话费，electricity电费，water水费,network网费,必填
                break;
            case Api.NETWORK_TYPE:
                setTitle("缴纳网费");
                initNetworkView();

                reqParamsRecharge.setInvestType("network");//充值类型：mobile话费，electricity电费，water水费,network网费,必填
                break;
        }

        et_convenient_payment_bill_no.setOnDrawableClickListener(new MonitorDrawableEventEditText.OnDrawableClickListener() {
            @Override
            public void onEndClick() {
                //扫码
                showMessage("开发中...");
            }
        });
    }

    private void initElectricityView() {
        i_convenient_payment_mobile.setVisibility(View.GONE);
        ll_convenient_payment_mobile.setVisibility(View.GONE);
        et_convenient_payment_bill_no.setHint("请输入账单号或扫码识别");
    }

    private void initWaterView() {
        i_convenient_payment_date.setVisibility(View.GONE);
        ll_convenient_payment_date.setVisibility(View.GONE);
        tv_convenient_payment_bill_no_l.setText("账户号");
        et_convenient_payment_bill_no.setHint("请输入账户号或扫码识别");
    }

    private void initNetworkView() {
        i_convenient_payment_mobile.setVisibility(View.GONE);
        ll_convenient_payment_mobile.setVisibility(View.GONE);
        i_convenient_payment_date.setVisibility(View.GONE);
        ll_convenient_payment_date.setVisibility(View.GONE);
        tv_convenient_payment_bill_no_l.setText("账户号");
        et_convenient_payment_bill_no.setHint("请输入账户号或扫码识别");
    }

    @OnClick({R.id.tv_convenient_payment_service_provider, R.id.ll_convenient_payment_date_r, R.id.tv_release_rent_seeking_bottom_operation,
            R.id.tv_Contact_customer_service})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_convenient_payment_service_provider:
                // 选服务商
                if (mServiceProviderList == null) {
                    assert mPresenter != null;
                    mPresenter.getServiceProvider(bisType);
                } else {
                    showServiceProviderList();
                }
                break;
            case R.id.ll_convenient_payment_date_r:
                ExtensionUtilKt.showDateDialog(this, PickerDateUtil.getDateForString(PickerDateUtil.getToday()), new CustomDatePickerDialog.OnDateSelectedListener() {
                    @Override
                    public void onDateSelected(int[] dates) {
                        StringBuilder sb = new StringBuilder();
                        sb.append(dates[0]);
                        sb.append("-");
                        if (dates[1] > 9) {
                            sb.append(dates[1]);
                        } else {
                            sb.append("0").append(dates[1]);
                        }
                        sb.append("-");
                        if (dates[2] > 9) {
                            sb.append(dates[2]);
                        } else {
                            sb.append("0").append(dates[2]);
                        }
                        tv_convenient_payment_date.setText(sb.toString());
                        reqParamsRecharge.setExpirationTime(PickerDateUtil.appendDefTime(sb.toString()));
                    }

                    @Override
                    public void onCancel() {
                        ArmsUtils.makeText(ConvenientPaymentActivity.this, getString(R.string.cancel));
                    }
                });
                break;
            case R.id.tv_release_rent_seeking_bottom_operation:
                KeyboardUtils.hideSoftInput(this);
                if (StringUtils.isTrimEmpty(reqParamsRecharge.getServiceProvider())) {
                    showMessage("请选择服务商");
                    return;
                }
                if (StringUtils.isTrimEmpty(et_convenient_payment_amount.getText().toString())) {
                    showMessage("请输入账号");
                    return;
                }

                switch (bisType) {
                    case Api.ELECTRICITY_TYPE:
                        if (StringUtils.isTrimEmpty(reqParamsRecharge.getExpirationTime())) {
                            showMessage("请选择到期日期");
                            return;
                        }
                        break;
                    case Api.NETWORK_TYPE:
                        if (StringUtils.isTrimEmpty(et_convenient_payment_mobile.getText().toString())) {
                            showMessage("请输入电话号码");
                            return;
                        }
                        reqParamsRecharge.setMobile(et_convenient_payment_mobile.getText().toString());
                        break;
                }

                if (StringUtils.isTrimEmpty(et_convenient_payment_amount.getText().toString())) {
                    showMessage(et_convenient_payment_amount.getHint().toString());
                    return;
                }
                reqParamsRecharge.setAccountNumber(Objects.requireNonNull(et_convenient_payment_bill_no.getText()).toString());
                reqParamsRecharge.setActuallyPayMoney(et_convenient_payment_amount.getText().toString());
                reqParamsRecharge.setTotalMoney(et_convenient_payment_amount.getText().toString());

                assert mPresenter != null;
                mPresenter.getExchangeRate(et_convenient_payment_amount.getText().toString());
                break;
            case R.id.tv_Contact_customer_service:
                // todo 联系客服
                break;
        }
    }

    @Override
    public void showLoading() {

    }

    @Override
    public void hideLoading() {

    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        ArmsUtils.snackbarText(message);
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {
        finish();
    }

    private List<HousePayWayBean> mHousePayWayBeans;

    @Override
    public void getPayWaySuccess(List<HousePayWayBean> housePayWayBeans) {
        if (housePayWayBeans != null) {
            mHousePayWayBeans = housePayWayBeans;
            showPayView();
        } else {
            showMessage("支付方式获取失败");
        }
    }

    private ExchangeRateBean mExchangeRateBean;

    @Override
    public void getExchangeRateSuccess(ExchangeRateBean exchangeRateBean) {
        if (exchangeRateBean != null) {
            mExchangeRateBean = exchangeRateBean;
            assert mPresenter != null;
            mPresenter.getPayWay();
        } else {
            showMessage("汇率获取失败");
        }
    }

    private CustomPopupWindow customPopupWindow;//支付
    private int selectPayWayIndex = -1;

    private void showPayView() {
        customPopupWindow = payPopupWindow(this, ll_root_view, mHousePayWayBeans, mExchangeRateBean, selectIndex -> selectPayWayIndex = selectIndex, v -> {
            if (selectPayWayIndex < 0) {
                showMessage("请选择支付方式");
            } else {
                if (reqParamsRecharge == null) {
                    reqParamsRecharge = new ReqParamsRecharge();
                }

                reqParamsRecharge.setActuallyPayMoney(et_convenient_payment_amount.getText().toString());
//                reqParamsRecharge.setActuallyPayMoney("0.01");
                switch (bisType) {
                    case Api.ELECTRICITY_TYPE:
                        reqParamsRecharge.setDescription("缴纳电费，账号：" + Objects.requireNonNull(et_convenient_payment_bill_no.getText()).toString());
                        break;
                    case Api.WATER_TYPE:
                        reqParamsRecharge.setDescription("缴纳水费，账号：" + Objects.requireNonNull(et_convenient_payment_bill_no.getText()).toString());
                        break;
                    case Api.NETWORK_TYPE:
                        String mobile = et_convenient_payment_mobile.getText().toString();
                        reqParamsRecharge.setMobile(mobile);
                        reqParamsRecharge.setDescription("缴纳网费，账号：" + Objects.requireNonNull(et_convenient_payment_bill_no.getText()).toString());
                        break;
                }
                reqParamsRecharge.setExchangeRate(mExchangeRateBean.getExchangeRate());
                reqParamsRecharge.setPayWay(mHousePayWayBeans.get(selectPayWayIndex).getCategory());//支付方式 ，微信，支付宝等等(从数据字典(PAY_METHOD)查询，取[category]值，如:alipay,wechat),必填
                reqParamsRecharge.setTotalMoney(et_convenient_payment_amount.getText().toString());
//                reqParamsRecharge.setTotalMoney("0.01");
                reqParamsRecharge.setTradeType("APP");//交易方式[APP、h5]，传字符,必填

                assert mPresenter != null;
                if ("alipay".equals(mHousePayWayBeans.get(selectPayWayIndex).getCategory())) {
                    mPresenter.rechargeCallCharge4AliPay(reqParamsRecharge);
                } else {
                    mPresenter.rechargeCallCharge4Wx(reqParamsRecharge);
                }
            }
        }, v -> customPopupWindow.dismiss());
        customPopupWindow.show();
    }

    //微信支付成功后回调
    @Subscriber(mode = ThreadMode.MAIN)
    public void wxPayFinish(BaseResp baseResp) {
        if (baseResp.errCode == BaseResp.ErrCode.ERR_OK) {
            paySuccess();
        }
    }

    @Override
    public void paySuccess() {
        showMessage(getString(R.string.pay_success));
        if (customPopupWindow != null) {
            customPopupWindow.dismiss();
        }
        killMyself();
    }

    @Override
    public void rechargeCallCharge4AliPaySuccess(String result) {
        if (!StringUtils.isTrimEmpty(result)) {
            assert mPresenter != null;
            mPresenter.payForAli(this, result);
        }
    }

    @Override
    public void rechargeCallCharge4WxSuccess(MemberPayResultBean result) {
        if (result != null) {
            assert mPresenter != null;
            mPresenter.payForWX(this, result);
        }
    }

    @Override
    public void getServiceProviderSuccess(List<HousePayWayBean> serviceProviderList) {
        if (serviceProviderList != null) {
            mServiceProviderList = serviceProviderList;
            showServiceProviderList();
        }
    }

    private void showServiceProviderList() {
        List<String> serviceProviderNameList;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
            serviceProviderNameList = mServiceProviderList.stream().map(HousePayWayBean::getName).collect(Collectors.toList());
        } else {
            serviceProviderNameList = new ArrayList<>();
            for (HousePayWayBean bean : mServiceProviderList) {
                serviceProviderNameList.add(bean.getName());
            }
        }
        ExtensionUtilKt.showDataPw(this, "选择服务商", serviceProviderNameList, 0, new DataPickerDialog.OnDataSelectedListener() {
            @Override
            public void onDataSelected(String itemValue, int position) {
                tv_convenient_payment_service_provider.setText(itemValue);
                reqParamsRecharge.setServiceProvider(mServiceProviderList.get(position).getDictId());
            }

            @Override
            public void onCancel() {
                ArmsUtils.makeText(ConvenientPaymentActivity.this, getString(R.string.cancel));
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        KeyboardUtils.hideSoftInput(this);
    }
}
